package org.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.app.dto.UserLoginDTO;
import org.app.dto.UserRegisterDTO;
import org.app.entity.User;
import org.app.exception.BusinessException;
import org.app.mapper.UserMapper;
import org.app.service.UserService;
import org.app.util.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Override
    public Map<String, Object> login(UserLoginDTO loginDTO) {
        // 查询用户
        User user = getByUsername(loginDTO.getUsername());
        
        // 判断用户是否存在
        if (user == null) {
            throw new BusinessException(400, "用户名或密码错误");
        }
        
        // 判断密码是否正确
        String encryptPassword = DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes());
        if (!encryptPassword.equals(user.getPassword())) {
            throw new BusinessException(400, "用户名或密码错误");
        }
        
        // 判断用户状态
        if (user.getStatus() == 0) {
            throw new BusinessException(400, "账号已被禁用");
        }
        
        // 生成token
        String token = jwtUtil.generateToken(user.getId(), user.getUsername());
        
        // 返回结果
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        user.setPassword(null); // 不返回密码
        map.put("user", user);
        
        return map;
    }
    
    @Override
    public void register(UserRegisterDTO registerDTO) {
        // 判断用户名是否已存在
        User existUser = getByUsername(registerDTO.getUsername());
        if (existUser != null) {
            throw new BusinessException(400, "用户名已存在");
        }
        
        // 创建新用户
        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);
        
        // 设置默认昵称
        if (!StringUtils.hasText(user.getNickname())) {
            user.setNickname(user.getUsername());
        }
        
        // 设置默认头像
        user.setAvatar("/static/avatar/default.png");
        
        // 加密密码
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        
        // 设置状态为正常
        user.setStatus(1);
        
        // 设置逻辑删除标记
        user.setIsDeleted(0);
        
        // 保存用户
        save(user);
    }
    
    @Override
    public Page<User> getUserPage(Integer pageNum, Integer pageSize, String keyword) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        
        // 模糊查询
        if (StringUtils.hasText(keyword)) {
            wrapper.like(User::getUsername, keyword)
                    .or()
                    .like(User::getNickname, keyword)
                    .or()
                    .like(User::getPhone, keyword);
        }
        
        // 排序
        wrapper.orderByDesc(User::getCreateTime);
        
        // 分页查询
        Page<User> page = new Page<>(pageNum, pageSize);
        return page(page, wrapper);
    }
    
    @Override
    public void updateUserStatus(Long userId, Integer status) {
        // 查询用户
        User user = getById(userId);
        if (user == null) {
            throw new BusinessException(400, "用户不存在");
        }
        
        // 更新状态
        User update = new User();
        update.setId(userId);
        update.setStatus(status);
        updateById(update);
    }
    
    @Override
    public User getByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return getOne(wrapper);
    }

    @Override
    public String resetPassword(Long userId) {
        return "";
    }
    
    @Override
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        // 查询用户
        User user = getById(userId);
        if (user == null) {
            throw new BusinessException(400, "用户不存在");
        }
        
        // 验证旧密码
        String encryptOldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (!encryptOldPassword.equals(user.getPassword())) {
            return false;
        }
        
        // 更新密码
        User update = new User();
        update.setId(userId);
        update.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
        updateById(update);
        
        return true;
    }
    
    @Override
    public String uploadAvatar(Long userId, MultipartFile file) throws Exception {
        // 获取文件扩展名
        String fileName = file.getOriginalFilename();
        String fileExtension = "";
        if (fileName != null && fileName.contains(".")) {
            fileExtension = fileName.substring(fileName.lastIndexOf("."));
        }
        
        // 生成新文件名
        String newFileName = userId + "_" + System.currentTimeMillis() + fileExtension;
        
        // 确定保存路径（改为upload目录）
        String uploadPath = System.getProperty("user.dir") + "/upload/avatar/";
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        
        // 保存文件
        File dest = new File(uploadPath + newFileName);
        file.transferTo(dest);
        
        // 更新用户头像URL（路径也需要修改）
        String avatarUrl = "/upload/avatar/" + newFileName;
        User update = new User();
        update.setId(userId);
        update.setAvatar(avatarUrl);
        updateById(update);
        
        return avatarUrl;
    }
} 